package com.eastcom.groovy.distributor



import org.apache.commons.dbcp.BasicDataSource
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

import com.eastcom.groovy.provider.DynamicBeanRegisterProvider;
import com.eastcom.groovy.provider.SpringContextProvider;
import com.eastcom.groovy.tools.file.JaxbUtil
import com.sun.org.apache.bcel.internal.generic.NEW;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Date;
import java.util.Map;


/**
 * 数据处理器。 数据处理器的主要功能由以下几个步骤来描述: 1.接收客户端(DPAdmin)来的数据; 2.对数据进行校验，过滤(过滤未实现);
 * 3.将合法数据进行封装，送入队列保存
 *
 * @author 张海峰
 * @version 1.0
 */
public class DPService {
	/** DOCUMENT ME! */
	static Logger logger = Logger.getLogger(DPService.class.getName());
	String port;
	String rootPath
	public static Map<String,String> table = new HashMap()
	public static Map<String, Map<String,String>> feild = new HashMap<String, Map<String,String>>()
	public static Map<String, String> dataType = new HashMap()
	public static Map<String, String> redirector = new HashMap()
	public static Map<String, List<String>> actionRuleList = new HashMap()

	/**
	 * Creates a new DPService object.
	 *
	 * @param rootPath DOCUMENT ME!
	 */
	public DPService()  throws Exception {

	}


	public void startService() throws Exception
	{
		try {
			ServerSocket ss = new ServerSocket(Integer.valueOf(port));
			if(rootPath.endsWith("/")){
				loadMappingRule(rootPath+"config/mapping_rule.xml")
				loadRedirector(rootPath+"config/redirector.xml")
				loadActionRule(rootPath+"config/action_rule.xml")
			}else{
				loadMappingRule(rootPath+"/config/mapping_rule.xml")
				loadRedirector(rootPath+"/config/redirector.xml")
				loadActionRule(rootPath+"/config/action_rule.xml")
			}
			logger.info("S.T.O.P.E. PROCESSOR start success @" + new Date());
			System.out.println("S.T.O.P.E. PROCESSOR start success @" + new Date());

			while (true) {
				Socket conn = null;
				try {
					conn = ss.accept();
					if(conn == null){
						continue
					}
					WorkerThread workThread = new WorkerThread(conn)
				} catch (Exception e) {
					System.out.println(e.getMessage());
					StackTraceElement[] ste = e.getStackTrace();
					logger.error(e);
					logger.error(ste[ste.length - 1]);
					conn = null;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private static boolean loadRedirector(String file){
		Redirector redirectorConfig = JaxbUtil.converyFileToJavaBean(file, "UTF-8", Redirector.class);
		println  redirectorConfig
		if(redirectorConfig == null){
			return false
		}
		redirectorConfig.collectors.collectorList.each {
			println it.driver
			Map<String,Object> properties = new HashMap()
			properties.put("driverClassName", it.driver)
			properties.put("url", it.url)
			properties.put("username", it.user)
			properties.put("password", it.password)
			properties.put("maxActive", 600)
			properties.put("validationQuery", true)
			properties.put("testOnBorrow", true)
			properties.put("maxIdle", 10)
			properties.put("maxWait", 300)
			properties.put("poolPreparedStatements", true)
			if(it.driver.contains("oracle")){
				properties.put("validationQuery", "SELECT 1 from dual")
			}else{
				properties.put("validationQuery", "SELECT 1")
			}
			println "注册bean="+it.name
			DynamicBeanRegisterProvider provider = SpringContextProvider.getBean("beanRegister")
			provider.addBeanService(it.name, "org.apache.commons.dbcp.BasicDataSource", properties)
		}
	}

	private static boolean loadActionRule(String file){
		ActionRule actionRule = JaxbUtil.converyFileToJavaBean(file, "UTF-8", ActionRule.class);
		for(int i = 0; i < actionRule.eventList.size(); i++){
			List<String> target = actionRule.eventList.get(i).action.targetList
			if(target == null ||target.isEmpty()){
				continue
			}
			actionRuleList.put(actionRule.eventList.get(i).tid, target)
			println actionRule.eventList.get(i).tid+"--ff---"+target.size()
		}
	}

	private static boolean loadMappingRule(String file){
		MappingRule mappingRule = JaxbUtil.converyFileToJavaBean(file, "UTF-8", MappingRule.class);
		System.out.println(mappingRule);
		if(mappingRule == null){
			return false
		}
		println mappingRule.targetZone.targetList
		mappingRule.targetZone.targetList.each {
			println  it.tid+"---"+it.name
			table.put(it.tid,it.name)
		}

		mappingRule.fieldZone.feildList.each {
			println  it.tid+"---"+it.name
			if(feild.keySet().contains(it.tid)){
				feild.get(it.tid).put(it.seqid,it.name)
				feild.get(it.tid).put(it.seqid+"_type",it.dtid)
			}else{
				println "------------ddddddddddddddddddddddddd"
				Map<String, String> temp = new HashMap<String, String>()
				temp.put(it.seqid, it.name)
				feild.put(it.tid, temp)
			}
		}
		mappingRule.dataTypeZone.typeList.each {
			println  it.dtid+"---"+it.name+"--"+it.format
			dataType.put(it.dtid, it.name)
		}
		return true
	}

	public String getPort() {
		return port;
	}


	public void setPort(String port) {
		this.port = port;
	}


	public String getRootPath() {
		return rootPath;
	}


	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}


	/**
	 * DOCUMENT ME!
	 *
	 * @param args DOCUMENT ME!
	 */
	public static void main(String[] args) {
		if (args.length < 2) {
			System.out.println("请指定配置文件路径，以及服务端口号,如/export/home/ipnet/ 9003");

			return;
		}
		try
		{
			DPService dps = new DPService(args[0],Integer.valueOf(args[1]));

		}catch(Exception e)
		{
			e.printStackTrace();
			System.out.println(e.getMessage());
			System.exit(0);
		}
		//        String root = "D://eclipse//workspace//stope//source";
		//        DPService dps = new DPService(root);
		//
	}
}

